<template>
  <div class="md-node" :style="{ width: width + 'px', height: height + 'px' }" @wheel.stop="handleWheel"
       @dblclick.stop.prevent="handleDoubleClick"
  >
    <div class="title-container" style="border-bottom: 1px solid #ddd;padding:10px;" :contenteditable="true" @blur="(e) => {
      titleBlur(e)
    }">
      {{ properties?.title }}
    </div>
    <div class="md-content" v-html="renderedContent" :style="{ width: '100%', height: '100%', overflow: 'auto' }"
      :contenteditable="true" @blur="(e) => {
        contentBlur(e)
      }">
    </div>


  </div>
</template>

<script>
import { EventType } from '@logicflow/core'
import { vueNodesMap } from '@logicflow/vue-node-registry'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

export default {
  name: 'MDNode',
  inject: ['getNode', 'getGraph'],
  data() {
    return {
      properties: {},
      isEditing: false,
      editContent: '',
      mdContent: '# 标题\n\n这是一个Markdown节点\n\n- 双击进入编辑模式\n- Ctrl+Enter保存内容',
      width: 200,
      height: 150
    }
  },
  computed: {
    renderedContent() {
      if (!this.mdContent) {
        return '<p>双击编辑内容</p>'
      }
      // 使用marked解析Markdown
      const rawHtml = marked(this.mdContent)
      // 使用DOMPurify清理HTML，防止XSS攻击
      return DOMPurify.sanitize(rawHtml)
    }
  },
  mounted() {
    console.log('=== MDNode mounted 开始 ===')
    console.log('this.getNode:', this.getNode)
    console.log('this.getGraph:', this.getGraph)

    if (!this.getNode || !this.getGraph) {
      console.error('MDNode: inject依赖注入失败，getNode或getGraph未定义')
      console.log('当前组件实例:', this)
      return
    }

    const node = this.getNode()
    const graph = this.getGraph()

    console.log('MDNode mounted, node:', node)
    console.log('MDNode mounted, graph:', graph)

    if (!node) {
      console.error('MDNode: 无法获取节点实例')
      console.log('可能原因: 1.节点未正确注册 2.依赖注入失败 3.组件挂载时机问题')
      return
    }

    if (!graph) {
      console.error('MDNode: 无法获取图实例')
      return
    }

    // 初始化节点属性
    const properties = node.getProperties() || {}
    console.log('MDNode properties:', properties)
    this.properties = properties;

    if (properties.mdContent) {
      this.mdContent = properties.mdContent
    }
    if (properties.width) {
      this.width = properties.width
    }
    if (properties.height) {
      this.height = properties.height
    }


    // 监听节点属性变化
    graph.eventCenter.on(EventType.NODE_PROPERTIES_CHANGE, (eventData) => {
      const keys = eventData.keys
      const content = vueNodesMap[node.type]

      if (content && eventData.id === node.id) {
        const { effect } = content
        if (!effect || keys.some((key) => effect.includes(key))) {
          console.log('MDNode属性变化:', eventData)

          // 更新内容
          if (eventData.properties.mdContent !== undefined) {
            this.mdContent = eventData.properties.mdContent
          }

          // 更新尺寸
          if (eventData.properties.width !== undefined) {
            this.width = eventData.properties.width
          }
          if (eventData.properties.height !== undefined) {
            this.height = eventData.properties.height
          }
        }
      }
    })
  },
  methods: {
    // 开始编辑
    startEdit() {
      this.isEditing = true
      this.editContent = this.mdContent

      // 下一帧聚焦到textarea
      this.$nextTick(() => {
        if (this.$refs.textareaRef) {
          this.$refs.textareaRef.focus()
        }
      })
    },

    // 保存内容
    saveContent() {
      const node = this.getNode()

      // 更新本地状态
      this.mdContent = this.editContent
      this.isEditing = false

      // 更新节点属性
      node.setProperty('mdContent', this.editContent)

      console.log('保存Markdown内容:', this.editContent)
    },
    titleBlur(e) {
      const node = this.getNode()
      node.setProperty('title', e.target.innerHTML
      )

    },
    contentBlur(e) {
      const node = this.getNode()
      node.setProperty('mdContent', e?.target?.innerHTML)
    },

    // 取消编辑
    cancelEdit() {
      this.isEditing = false
      this.editContent = this.mdContent
    },

    // 处理键盘事件
    handleKeydown(event) {
      // Ctrl+Enter 保存
      if (event.ctrlKey && event.key === 'Enter') {
        event.preventDefault()
        this.saveContent()
      }
      // Escape 取消编辑
      else if (event.key === 'Escape') {
        event.preventDefault()
        this.cancelEdit()
      }
    },

    // 失去焦点时的处理（可选：自动保存或取消）
    handleBlur() {
      // 这里可以选择自动保存或者什么都不做
      // 暂时不自动保存，让用户明确使用Ctrl+Enter
    },

    // 处理滚轮事件
    handleWheel(event) {
      // 阻止事件冒泡
      event.stopPropagation()
      // console.log('MdNode滚轮事件:', event.deltaY)
    },

    // 处理双击事件
    handleDoubleClick(event) {
      // 阻止事件冒泡
      event.stopPropagation()
      // console.log('MdNode双击事件触发')
      // 可以在这里添加双击后的具体逻辑，比如进入编辑模式
      // this.startEdit()
    }
  }
}
</script>

<style>
.md-node {
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  position: relative;
  overflow: hidden;
}

.edit-mode {
  width: 100%;
  height: 100%;
}

.md-textarea {
  border: none;
  outline: none;
  resize: none;
  padding: 8px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  background: #f9f9f9;
}

.view-mode {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.md-content {
  padding: 8px;
  font-size: 12px;
  line-height: 1.4;
}

.md-content h1 {
  font-size: 16px;
  margin: 0 0 8px 0;
}

.md-content h2 {
  font-size: 14px;
  margin: 0 0 6px 0;
}

.md-content h3 {
  font-size: 13px;
  margin: 0 0 4px 0;
}

.md-content p {
  margin: 0 0 8px 0;
}

.md-content ul,
.md-content ol {
  margin: 0 0 8px 0;
  padding-left: 20px;
}

.md-content li {
  margin: 2px 0;
}

.md-content code {
  background: #f0f0f0;
  padding: 2px 4px;
  border-radius: 2px;
  font-family: 'Courier New', monospace;
}

.md-content pre {
  background: #f0f0f0;
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 8px 0;
}

.md-content blockquote {
  border-left: 3px solid #ddd;
  padding-left: 8px;
  margin: 8px 0;
  color: #666;
}


</style>